package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func ClubManage(ctx *gin.Context) {
	Uid := ctx.Query("uid")
	uid, _ := strconv.Atoi(Uid)

	DB := common.GetDB()
	var myclubs []model.UserClub
	err := DB.Where("UID=? and Permission=? and QTime IS NULL", uid, 1).Find(&myclubs).Error

	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err)
		return
	}

	var clubs []model.Club
	var Mainimage []string
	var Images [][]model.CImage
	var Members [][]model.User
	var Position [][]string

	for _, myclub := range myclubs {
		var c model.Club
		err1 := DB.Where("Exist=? and id=?", 1, myclub.Cid).First(&c).Error
		if err1 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err11111:", err1)
			return
		}
		clubs = append(clubs, c)

		var i model.CImage
		err2 := DB.Where("Cid=? AND Main=?", myclub.Cid, 1).Find(&i).Error
		if err2 != nil {
			if err2 == gorm.ErrRecordNotFound {
				Mainimage = append(Mainimage, "")
				continue
			} else {
				response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
				log.Println("err2:", err2)
				return
			}
		}
		Mainimage = append(Mainimage, i.Path)

		var images []model.CImage
		var m []model.CImage
		err3 := DB.Where("Cid=? AND Main=?", myclub.Cid, 0).Find(&m).Error
		if err3 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err3:", err3)
			return
		}
		for _, m := range m {
			images = append(images, m)
		}

		var clubuser []model.UserClub
		err5 := DB.Where("Cid=?", myclub.Cid).Find(&clubuser).Error
		if err5 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err5:", err5)
			return
		}

		var members []model.User
		var position []string
		for _, cuser := range clubuser {
			var user model.User
			err6 := DB.Where("uid=?", cuser.UID).First(&user).Error
			if err6 != nil {
				response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
				log.Println("err6:", err6)
				return
			}
			members = append(members, user)
			position = append(position, cuser.Position)
		}
		Images = append(Images, images)
		Members = append(Members, members)
		Position = append(Position, position)
	}
	// 返回查询结果
	response.Success(ctx, gin.H{"clubs": clubs, "MainImages": Mainimage, "Images": Images, "members": Members, "position": Position}, "社团管理信息获取成功")
}

func ModifyClubInfo(ctx *gin.Context) {
	Cid := ctx.PostForm("cid")
	cid, _ := strconv.Atoi(Cid)
	introduction := ctx.PostForm("introduction")
	outstanding := ctx.PostForm("outstanding")

	DB := common.GetDB()
	err := DB.Exec("UPDATE clubs SET Introduction= ?,Outstanding=? WHERE id=?", introduction, outstanding, cid).Error
	if err != nil {
		log.Println("err:", err)
		response.Response(ctx, http.StatusBadRequest, 422, nil, "修改社团信息失败，请重试！")
		return
	}
	response.Success(ctx, nil, "修改用户名成功！")
}
func UploadHandler(c *gin.Context) {
	w := c.Writer
	r := c.Request
	cid := c.PostForm("cid")
	id, _ := strconv.Atoi(cid)
	Kind := c.PostForm("kind")
	kind, _ := strconv.Atoi(Kind)
	result := UploadImages(w, r, cid, kind)
	if result != "error" {
		ModifyMainImage(c, id, result)
	}
}

func UploadImages(w http.ResponseWriter, r *http.Request, cid string, kind int) string {
	if r.Method != "POST" {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return "error"
	}

	err := r.ParseMultipartForm(10 << 20) // 设置最大文件大小为 10MB
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return "error"
	}

	file, _, err := r.FormFile("file")
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return "error"
	}

	FileErr := file.Close()
	if err != nil {
		log.Println("Error closing file:", FileErr)
		return "error"
	}

	client, err := oss.New("https://oss-cn-beijing.aliyuncs.com", "LTAI5t8CXeoYfcjaXDNGNSjK", "Wg2oijuZdcY7zsY7QoAHlzALtHHFbK")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return "error"
	}

	var objectName string
	bucketName := "digital-baituan-filestore"
	dir := "images/"
	if kind == 0 {
		objectName = dir + cid + "_main.png"
	} else if kind == 1 {
		objectName = dir + cid + "_main.jpg"
	}

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return "error"
	}

	err = bucket.PutObject(objectName, file)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return "error"
	}

	newURL := "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + objectName
	return newURL
}

func UploadAllImages(w http.ResponseWriter, r *http.Request, cid string, kind []int) []string {
	if r.Method != "POST" {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return nil
	}

	err := r.ParseMultipartForm(10 << 20) // 设置最大文件大小为 10MB
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return nil
	}

	files, _ := r.MultipartForm.File["returnfile"]

	if len(files) == 0 {
		http.Error(w, "No file uploaded", http.StatusBadRequest)
		return nil
	}

	client, err := oss.New("https://oss-cn-beijing.aliyuncs.com", "LTAI5t8CXeoYfcjaXDNGNSjK", "Wg2oijuZdcY7zsY7QoAHlzALtHHFbK")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return nil
	}

	bucketName := "digital-baituan-filestore"
	dir := "images/"
	var results []string

	for i, file := range files {
		fileHandle, err := file.Open()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			continue
		}

		defer fileHandle.Close()

		objectName := generateUniqueName(dir, cid, kind[i])

		bucket, err := client.Bucket(bucketName)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return nil
		}

		err = bucket.PutObject(objectName, fileHandle)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			continue
		}

		newURL := "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + objectName
		results = append(results, newURL)
	}

	return results
}

func ModifyMainImage(ctx *gin.Context, id int, url string) {
	DB := common.GetDB()
	var cimage model.CImage
	err := DB.Where("Cid=? AND Main=?", id, 1).Delete(&cimage).Error
	if err != nil {
		log.Println("err", err)
		return
	}

	Cimage := model.CImage{
		Cid:  id,
		Main: 1,
		Path: url,
	}

	err1 := DB.Create(&Cimage).Error
	if err1 != nil {
		response.Response(ctx, http.StatusInternalServerError, 400, nil, "创建失败，请重试")
		log.Println("err1:", err1)
		return
	}

	response.Success(ctx, gin.H{"url": url}, "修改成功")
}

func ModifyImages(ctx *gin.Context, id int, deleted []int, urls []string) {
	Uid := ctx.PostForm("uid")
	uid, _ := strconv.Atoi(Uid)

	DB := common.GetDB()
	result := DB.Begin()

	var cimage []model.CImage
	err := result.Where("CIid in (?)", deleted).Delete(&cimage).Error
	if err != nil {
		log.Println("err", err)
		result.Rollback() // 回滚事务
		response.Response(ctx, http.StatusInternalServerError, 402, nil, "删除失败，请重试")
		return
	}

	for _, url := range urls {
		Cimage := model.CImage{
			Cid:  id,
			Main: 0,
			Path: url,
		}

		err := result.Create(&Cimage).Error
		if err != nil {
			result.Rollback() // 回滚事务
			response.Response(ctx, http.StatusInternalServerError, 400, nil, "创建失败，请重试")
			return // 或者您可以选择继续处理其他URL，而不是立即返回
		}
	}

	err = result.Commit().Error
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 400, nil, "事务提交失败，请重试")
		return
	}

	var myclubs []model.UserClub
	err1 := DB.Where("UID=? and Permission=? AND QTime IS NULL", uid, 1).Find(&myclubs).Error
	if err1 != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err1:", err1)
		return
	}

	var Images [][]model.CImage
	for _, myclub := range myclubs {
		var images []model.CImage
		var m []model.CImage
		err2 := DB.Where("Cid=? AND Main=?", myclub.Cid, 0).Find(&m).Error

		if err2 != nil {
			if err2 == gorm.ErrRecordNotFound {
				continue
			} else {
				response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
				log.Println("err2:", err2)
				return
			}
		}
		for _, m := range m {
			images = append(images, m)
		}
		Images = append(Images, images)
	}

	response.Success(ctx, gin.H{"images": Images}, "修改成功")
}

func UploadImageHandler(c *gin.Context) {
	w := c.Writer
	r := c.Request
	cid := c.PostForm("cid")
	id, _ := strconv.Atoi(cid)

	deleteIDs := c.PostForm("deleted")
	deleteIDInts, err := stringToIntSlice(deleteIDs) // 转换为[]int
	if err != nil {
		http.Error(w, "Invalid deleteIDs format", http.StatusBadRequest)
	}

	Kind := c.PostForm("kind")
	kindInts, err := stringToIntSlice(Kind) // 转换为[]int
	if err != nil {
		http.Error(w, "Invalid kind format", http.StatusBadRequest)
		return
	}

	results := UploadAllImages(w, r, cid, kindInts)
	if results != nil {
		ModifyImages(c, id, deleteIDInts, results)
	}
}

func stringToIntSlice(s string) ([]int, error) {
	strSlice := strings.Split(s, ",")
	intSlice := make([]int, len(strSlice))
	for i, str := range strSlice {
		num, err := strconv.Atoi(strings.TrimSpace(str))
		if err != nil {
			return nil, err
		}
		intSlice[i] = num
	}
	return intSlice, nil
}

func generateUniqueName(dir, cid string, i int) string {
	currentTime := time.Now().Format("20060102_150405")
	var uniqueName string
	if i == 0 {
		uniqueName = dir + cid + "_" + currentTime + ".png"
	}
	if i == 1 {
		uniqueName = dir + cid + "_" + currentTime + ".jpg"
	}
	return uniqueName
}
